﻿using System;
using log4net;
using log4net.Appender;
using System.Collections;
using log4net.Repository.Hierarchy;
using System.IO;
using System.Globalization;
using System.Windows.Forms;
using System.Linq;

namespace SysSUFront
{
    public class TextBoxAppender : AppenderSkeleton
    {
        public TextBoxAppender() { }

        protected override void Append(log4net.Core.LoggingEvent LoggingEvent)
        {
            if (Out != null && !Out.IsDisposed)
            {
                var stringWriter = new StringWriter(CultureInfo.InvariantCulture);
                Layout.Format(stringWriter, LoggingEvent);
                if (Out.InvokeRequired)
                {
                    Out.BeginInvoke(new MethodInvoker(delegate()
                    {
                        Out.AppendText(stringWriter.ToString());
                    }));
                }
                else
                {
                    Out.AppendText(stringWriter.ToString());
                }
            }
        }

        public TextBoxBase Out { get; set; }

        public static void SetTextBox(TextBoxBase tb)
        {
            Array.ForEach<TextBoxAppender>(
                GetAppenders().OfType<TextBoxAppender>().ToArray(),
                delegate(TextBoxAppender tbxa) { tbxa.Out = tb; });
        }

        private static IAppender[] GetAppenders()
        {
            var appenders = new ArrayList();
            appenders.AddRange(((Hierarchy)LogManager.GetRepository()).Root.Appenders);

            foreach (var log in LogManager.GetCurrentLoggers())
            {
                appenders.AddRange(((log4net.Repository.Hierarchy.Logger)log.Logger).Appenders);
            }

            return (IAppender[])appenders.ToArray(typeof(IAppender));
        }
    }
}
